<template>
  <div>
    <el-upload
      v-if="!flag"
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img
        v-if="imageUrl"
        v-imgError="defaultImg"
        :src="imageUrl"
        class="avatar"
      >
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <el-progress
      v-if="flag"
      type="circle"
      :percentage="percentage"
      :width="width"
    />
  </div>
</template>

<script>
import defaultImg from '@/assets/common/f778738c-e4f8-4870-b634-56703b4acafe.gif'
export default {
  name: 'UploadImg',
  props: ['imageUrl'],
  data() {
    return {
      // imageUrl: '',
      percentage: 0,
      flag: false,
      width: 178,
      defaultImg: defaultImg
    }
  },
  methods: {
    upload(file) {
      this.flag = true
      var COS = require('cos-js-sdk-v5')
      // SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
      var cos = new COS({
        SecretId: 'AKID4xaw2rQik23WlkSt3wYtxkGVTADAqGPH',
        SecretKey: 'dz4sQQDvOccNvDEyRdYDcjZ8QSCgtiHZ'
      })
      cos.putObject(
        {
          Bucket: 'it-wz-1308713081' /* 必须 */,
          Region: 'ap-nanjing' /* 存储桶所在地域，必须字段 */,
          Key: file.file.name /* 必须 */,
          StorageClass: 'STANDARD',
          Body: file.file, // 上传文件对象
          onProgress: (progressData) => {
            // console.log(progressData)
            const num = progressData.percent * 100
            const num1 = parseInt(num)
            // console.log(num)
            this.percentage = num1
          }
        },
        (err, data) => {
          // console.log(err || data)
          this.$emit('update:imageUrl', 'https://' + data.Location)
          this.$emit('success', 'https://' + data.Location)
          this.flag = false
        }
      )
      // this.$notify({
      //   type: 'success',
      //   title: '成功',
      //   message: '更新头像成功!',
      //   offset: 100
      // })
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      // const isPNG = file.type === 'image/png'
      // const isJpg = file.type === 'image/jpg'
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 10MB!')
      }
      return isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
